﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Donkey.Server.CommandProcessors;
using Donkey.Common;
using Donkey.Common.Commands;

namespace Donkey.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Clear();

            Console.Write("Command parser...");
            CommandParser.Init();
            Console.WriteLine("[OK]");

            Console.Write("Command parser...");
            CommandProcessorFabric.Init();
            Console.WriteLine("[OK]");

            Console.Write("Game server... ");
            using (var gameServer = new GameServer())
            {
                gameServer.Load();
                Console.WriteLine("[OK]");

                Console.Write("Request server... ");
                var networkServer = new NetworkServer<TcpRequestServer>(gameServer, Defaults.Port);
                networkServer.Start();
                Console.WriteLine("[OK]");

				//TODO: для отладки
				gameServer.CreateLobby("game");
				gameServer.CreateLobby("game1");
				gameServer.CreateLobby("game2");
				gameServer.CreateLobby("game3");
				gameServer.CreateLobby("qwerty");

                Console.WriteLine("Now you can type commands!");
                bool abort = false;
                while (!abort)
                {
                    var commandText = Console.ReadLine();
                    ClientCommand command = null;
                    try
                    {
                        command = CommandParser.Parse(commandText);
                    }
                    catch (GameServerException ex)
                    {
                        Console.WriteLine("Parse error: {0}", ex.Message);
                        continue;
                    }

                    try
                    {
                        var processor = CommandProcessorFabric.GetProcessor(command);
                        var result = processor.ExecuteOn(gameServer);
                        Console.WriteLine("Command result: {0}", processor.Answer.Success);
						if (processor.Answer.Success)
							Console.WriteLine(processor.Answer.ToString());
                    }
                    catch (GameServerException ex)
                    {
                        Console.WriteLine("Exception: {0}", ex.Message);
                    }
                    catch (NotImplementedException ex)
                    {
                        Console.WriteLine("No implementation: {0}", ex.Message);
                    }
                }
            }
        }
    }
}
